package com.baidu.bulls.stock.cat.demo.order.catutils;

import com.dianping.cat.Cat;
import com.dianping.cat.CatConstants;
import com.dianping.cat.message.Message;
import com.dianping.cat.message.Transaction;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

public class CatServletFilter implements Filter {
    String[] urlPatterns = new String[0];

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String patterns = filterConfig.getInitParameter("CatHttpModuleUrlPatterns");
       if (patterns != null){
           patterns = patterns.trim();
           urlPatterns = patterns.split(",");
           for (int i = 0; i < urlPatterns.length; i++) {
               urlPatterns[i] = urlPatterns[i].trim();
           }
       }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String url = request.getRequestURI();
        for (String urlPattern : urlPatterns) {
            if ( url.startsWith(urlPattern)){
                url = urlPattern;
            }
        }

        CatContext catContext = new CatContext();
        catContext.addProperty(Cat.Context.ROOT,request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_ROOT_MESSAGE_ID));
        catContext.addProperty(Cat.Context.PARENT,request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_PARENT_MESSAGE_ID));
        catContext.addProperty(Cat.Context.CHILD,request.getHeader(CatHttpConstants.CAT_HTTP_HEADER_CHILD_MESSAGE_ID));

        Transaction t = Cat.newTransaction(CatConstants.TYPE_URL, url);

        try {
            Cat.logEvent("Service.method",request.getMethod(), Message.SUCCESS,request.getRequestURI());
            Cat.logEvent("Service.host",request.getRemoteHost());
            chain.doFilter(servletRequest,servletResponse);
        } catch (Exception e) {
            t.setStatus(e);
            Cat.logError(e);
            throw e;
        } finally {
            t.complete();
        }
    }
}
